package com.yonyou.ucf.mdf.util;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
//import com.yonyou.iuap.bd.org.privateutil.AuthHttpClientUtils;
//import com.yonyou.ucf.util.PropertyUtil;
import com.sm.misc.BASE64Encoder;
import nc.vo.pub.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class BIPUtil {

    private static final Logger logger = LoggerFactory.getLogger(BIPUtil.class);

    /**
     * 获取登陆的地址
     * @param system             进行单点登录系统
     * @param userCode  获取零时单点登录返回的信息
     * @param thirdUCId  企业信息编码
     * @param baseURL  基准URL(https://euc.yonyoucloud.com)
     * @param redirectedURL  重定向地址(https://c3.yonyoucloud.com/login)
     * @return
     * @throws BusinessException
     */
    public static String getloginURL(String system, String userCode, String thirdUCId, String qycode, String baseURL, String redirectedURL) throws BusinessException {
        String loginURL = "";
        if("YHT".equals(system)){
            loginURL = String.format("%s/cas/thirdOauth2CodeLogin?thirdUCId=%s&code=%s&service=%s", baseURL, thirdUCId, userCode, encode(redirectedURL, true,qycode));
        }else if("YFK".equals(system)){
            loginURL = String.format("%s/cas/thirdOauth2CodeLogin?thirdUCId=%s&code=%s&service=%s", baseURL, thirdUCId, userCode, encode(redirectedURL, true,qycode));
        }
        return loginURL;
    }

    private static String encode(String url, boolean isNeedTenantId, String qycode)  throws BusinessException{
        try {
            if(isNeedTenantId){
                if(StringUtils.contains(url,"?")){
                    return URLEncoder.encode(url + "&tenantId=" + qycode, StandardCharsets.UTF_8.toString());
                }else {
                    return URLEncoder.encode(url + "?tenantId=" + qycode, StandardCharsets.UTF_8.toString());
                }
            }else {
                return URLEncoder.encode(url,StandardCharsets.UTF_8.toString());
            }
        }catch (Exception e){
            throw new BusinessException("url转义异常："+url);
        }
    }

    public static String getAccessToken(String apiUrl, String appKey, String appSecret) {
        String access_token = null;
        Map<String, Object> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("appKey", appKey);
        params.put("timestamp", System.currentTimeMillis());
        // 计算签名
        try {
            String signature = sign(params, appSecret);
            params.put("signature", signature);
            // 请求
            String httpResponse = HttpClientUtil.doGet(apiUrl, null, params);
            if (StringUtils.isNotBlank(httpResponse)) {
                access_token = JSONObject.parseObject(httpResponse).getJSONObject("data").getString("access_token");
//                access_token = JSONUtil.parseObj(JSONUtil.parseObj(httpResponse).get("data")).get("access_token").toString();
            }
        } catch (Exception e) {
        }
        return access_token;
    }

    /**
     * @param url
     * @param access_token
     * @param thirdUcId
     * @param userId
     * @return
     */
    public static String getThirdLoginCode(String url, String access_token, String thirdUcId, String userId) {
        String thirdLoginCode = null;
        Map queryParams = new HashMap();
        queryParams.put("access_token", access_token);
        Map bodyParams = new HashMap();
        bodyParams.put("thirdUcId", thirdUcId);
        bodyParams.put("userId", userId);
        String httpResponse = HttpClientUtil.doPost(url, null, queryParams, bodyParams);
        System.out.println("getThirdLoginCode  获取登录code返回的信息: " + httpResponse);
//        if (StringUtils.isNotBlank(httpResponse)) {
//            thirdLoginCode = JSONUtil.parseObj(JSONUtil.parseObj(httpResponse).get("data")).get("code")+"";
//        }
//        return thirdLoginCode;
        return httpResponse;
    }

    /**
     * 接口请求
     * @param url
     * @param queryParams
     * @param bodyParams
     * @return
     */
    public static String getPostQueryParamAndBodyParam(String url, Map queryParams, Map bodyParams) {
        String httpResponse = HttpClientUtil.doPost(url, null, queryParams, bodyParams);
        return httpResponse;
    }

    /**
     * 接口数据加密
     *
     * @param params
     * @param suiteSecret
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws UnsupportedEncodingException
     */
    public static String sign(Map<String, Object> params, String suiteSecret) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        // use tree map to sort params by name
        Map<String, Object> treeMap;
        if (params instanceof TreeMap) {
            treeMap = params;
        } else {
            treeMap = new TreeMap<>(params);
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
            stringBuilder.append(entry.getKey()).append(entry.getValue());
        }
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(suiteSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
        BASE64Encoder encode = new BASE64Encoder();
        String base64String = encode.encode(signData);
        return URLEncoder.encode(base64String, StandardCharsets.UTF_8);
    }

    /**
     * 单点登录内部登录
     * @param url
     * @param userId
     * @return
     * @throws Exception
     */
    public static String getUserLoginTokenLimitIps(String url, String userId) throws Exception {
        String userLoginToken = null;
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("userId", userId);
        String httpResponse = HttpClientUtil.doGet(url, null, paramsMap);
        if (StringUtils.isNotBlank(httpResponse)) {
            userLoginToken = JSONUtil.parseObj(httpResponse).get("token").toString();
        }
        return userLoginToken;
    }

    /**
     * 根据url下载文件流
     * @param urlStr
     * @return
     */
    public static InputStream getInputStreamFromUrl(String urlStr) {
        InputStream inputStream=null;
        try {
            //url解码
            URL url = new URL(java.net.URLDecoder.decode(urlStr, StandardCharsets.UTF_16));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(60 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            inputStream = conn.getInputStream();
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        return inputStream;
    }

    public static void callbackPlatformCommon(String logId, int status, String content) {
        // 回调调度任务
        JSONObject param = new JSONObject();
        param.put("status", status);
        param.put("id", logId);
        param.put("content", content);
        try {
            // 旧版本
//            String url = PropertyUtil.getPropertyByKey("domain.iuap-apcom-scheduler") + "/warning/warning/async/updateTaskLog";
            // sp517版本
//            String url = PropertyUtil.getPropertyByKey("domain.iuap-apcom-coderule") + "/warning/warning/async/updateTaskLog";
//            AuthHttpClientUtils.execPost(url, null, null, param.toString());
        } catch (Exception e) {
            logger.error("回调平台，更改任务状态异常 " + e.getMessage(), e);
        }
    }
}
